﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Xml.Linq;
using VPLink2013.Framework;

namespace VPLink2013.Webparts
{
    [ToolboxItemAttribute(false)]
    public class TrombinoscopeViewWebPart : ListViewWebPart, IXmlFileLinkedWebPart
    {
        #region Data

        private string _sourceXml;
        private string _selectedService;

        #endregion

        private readonly int _listTemplate = 104;
        public override int ListTemplate
        {
            get { return _listTemplate; }
        }

        private string _xmlFileURL;

        #region IXmlFileLinkedWebPart Members

        string IXmlFileLinkedWebPart.XmlFileURL
        {
            get
            {
                return XmlFileURL;
            }
            set
            {
                XmlFileURL = value;
            }
        }

        #endregion

        [Browsable(true), Category("Miscellaneous"),
        WebPartStorage(Storage.Shared),
        FriendlyName("XmlFileURL"),
        Description("URL of the xml file used in the WebPart."),
        DefaultValue("")]
        public string XmlFileURL
        {
            get
            {
                return _xmlFileURL;
            }
            set
            {
                _xmlFileURL = value;
            }
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolParts = new ToolPart[2];
            toolParts[0] = new XmlFileURLToolPart();
            toolParts[1] = new WebPartToolPart();
            return toolParts;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if (!string.IsNullOrEmpty(_xmlFileURL))
            {
                Page.RegisterRequiresControlState(this);

                if (string.IsNullOrEmpty(_sourceXml))
                {
                    SPSite site = SPContext.Current.Site;
                    SPWeb web = site.RootWeb;
                    try
                    {
                        _sourceXml = web.GetFileAsString(_xmlFileURL);
                    }
                    catch
                    {
                        _sourceXml = string.Empty;
                    }
                }

                if (!string.IsNullOrEmpty(_sourceXml))
                {
                    string param = ParamFrm("selectedService");
                    XDocument xDoc = XDocument.Parse(_sourceXml);
                    if (string.IsNullOrEmpty(param))
                    {
                        _selectedService = "DIR - DG";
                    }
                    else
                    {
                        _selectedService = param;
                    }
                }
            }
        }

        private string ParamFrm(string Name)
        {
            string strValue = ParamFrmNoTrim(Name).Trim();
            ContextTrace.AddTrace("ParamFrm : " + Name + " = " + strValue);
            return strValue;
        }
        private string ParamFrmNoTrim(string Name)
        {
            HttpRequest Request = Context.Request;
            string strValue;
            if (Request.Form.Count == 0)
            {
                strValue = Request.QueryString[Name];
            }
            else
            {
                strValue = Request.Form[Name];
                if (strValue == null || strValue == "undefined")
                {
                    strValue = Request.QueryString[Name];
                }
            }
            if (strValue == null || strValue == "undefined")
            {
                strValue = "";
            }
            //if (strValue != "")
            //{
            //    ContextTrace.AddTrace("ParamFrmNoTrim : " + Name + " = " + strValue);
            //}
            return strValue;
        }
        protected override void RenderWebPart(HtmlTextWriter output)
        {
            ContextTrace.AddTrace("RenderWebPart.A");
            if (!string.IsNullOrEmpty(_xmlFileURL))
            {
                if (!string.IsNullOrEmpty(_sourceXml))
                {
                    XDocument xDoc = XDocument.Parse(_sourceXml);
                    XElement selectedElem = SetSelectedService(xDoc.Root);

                    if (selectedElem != null)
                    {
                        string xslDoc = ListViewWebPart.GetPathForXSL("webpartTrombinoscopeView2.xsl");

                        int rowCount = 5;
                        int columnCount = 5;
                        if (selectedElem.Descendants("User").Count() > 0)
                        {
                            if (selectedElem.Elements("User").Count() > 0)
                            {
                                rowCount = selectedElem.Elements("User")
                                            .Max(u => int.Parse(u.Attribute("RowNumber").Value) + 1);
                            }
                        }
                        ContextTrace.AddTrace("Nombre de rows = " + rowCount);
                        XElement rowCountXElement = new XElement("RowCount");
                        rowCountXElement.SetValue(rowCount);
                        xDoc.Root.Add(rowCountXElement);

                        XElement columnCountXElement = new XElement("ColumnCount");
                        columnCountXElement.SetValue(columnCount);
                        xDoc.Root.Add(columnCountXElement);


                        string strXslTransformResult = ListViewWebPart.SetXslTransformer(xslDoc, xDoc);
                        output.Write(strXslTransformResult);
                    }
                }
                else
                {
                    output.Write("<div style=\"align:center\">Le fichier XML est invalide.</div>");
                }
            }
            else
            {
                output.Write("<div style=\"align:center\">Fichier XML non spécifié.</div>");
            }
            ContextTrace.AddTrace("RenderWebPart.B");
            ContextTrace.Save("", "TrombinoscopeView.txt");
        }

        /// <summary>
        /// Sets the selected service.
        /// </summary>
        /// <param name="xElement"></param>
        private XElement SetSelectedService(XElement xElement)
        {
            XElement selectedService = null;
            try
            {
                selectedService = xElement.Descendants("Service")
                                                   .First(s => s.Attribute("Code").Value == _selectedService);
            }
            catch { }
            if (selectedService != null)
            {
                selectedService.SetAttributeValue("Selected", "True");

                // Ajout de l'attribut SelectedDirection au noeud Direction
                // Cas on clique sur une direction
                if (selectedService.Parent.Name.LocalName.Equals("Services"))
                {
                    selectedService.SetAttributeValue("SelectedDirection", "True");
                }
                else
                {
                    // Cas on clique sur un département
                    if (selectedService.Parent.Parent.Name.LocalName.Equals("Services"))
                    {
                        selectedService.Parent.SetAttributeValue("SelectedDirection", "True");
                    }
                    else
                    {
                        // Cas on clique sur un Service
                        selectedService.Parent.Parent.SetAttributeValue("SelectedDirection", "True");
                    }
                }
            }
            return selectedService;
        }

        public string FormatLogin(string login)
        {
            string strLogin = login;
            int iPos = strLogin.IndexOf(@"\");
            if (iPos > 0)
            {
                strLogin = strLogin.Substring(iPos + 1);
            }
            return strLogin;
        }


        public string FormatPhoneNumber(string num)
        {
            string strNum = num;

            ContextTrace.AddTrace("Format initial : " + num);

            if (strNum.StartsWith("0"))
            {
                strNum = "+33(0) " + strNum.Substring(1);
            }
            if (strNum.StartsWith("+331"))
            {
                strNum = "+33(0) 1" + strNum.Substring(4);
            }
            strNum = strNum.Replace("  ", " ");

            ContextTrace.AddTrace("strNum : " + strNum);
            if (strNum.StartsWith("+33(0) "))
            {
                strNum = "+33(0) " + FormatInterne(strNum.Substring("+33(0) ".Length));
            }

            ContextTrace.AddTrace("Format final   : " + strNum);
            ContextTrace.AddTrace("------------------------------------------------------");
            return strNum;
        }

        private string FormatInterne(string num)
        {
            string strNum = num;
            strNum = strNum.Replace(" ", "").Replace(".", "");
            if (strNum.Length > 2)
            {
                strNum = strNum.Substring(0, 1) + "." + strNum.Substring(1);
            }
            if (strNum.Length > 5)
            {
                strNum = strNum.Substring(0, 4) + "." + strNum.Substring(4);
            }
            if (strNum.Length > 8)
            {
                strNum = strNum.Substring(0, 7) + "." + strNum.Substring(7);
            }
            if (strNum.Length > 11)
            {
                strNum = strNum.Substring(0, 10) + "." + strNum.Substring(10);
            }
            return strNum;
        }
    }
}
